package com.ruoyi.bbsAdmin.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bbsAdmin.domain.Content;
import com.ruoyi.bbsAdmin.domain.UserSchool;
import com.ruoyi.bbsAdmin.domain.bbs_user;
import com.ruoyi.bbsAdmin.domain.vo.commentVo;
import com.ruoyi.bbsAdmin.domain.vo.mainCommentRedisVo;
import com.ruoyi.bbsAdmin.mapper.ContentMapper;
import com.ruoyi.bbsAdmin.mapper.bbs_userMapper;
import com.ruoyi.bbsAdmin.service.RedisService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.bbsAdmin.mapper.CommentMapper;
import com.ruoyi.bbsAdmin.domain.Comment;
import com.ruoyi.bbsAdmin.service.ICommentService;

import javax.annotation.Resource;

/**
 * 评论Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-04-01
 */
@Service
public class CommentServiceImpl implements ICommentService 
{
    @Resource
    private CommentMapper commentMapper;

    @Resource
    private bbs_userMapper bbs_userMapper;

    @Resource
    private ContentMapper ContentMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedisService redisService;

    /**
     * 查询评论
     * 
     * @param commentid 评论主键
     * @return 评论
     */
    @Override
    public Comment selectCommentByCommentid(String commentid)
    {
        return commentMapper.selectCommentByCommentid(commentid);
    }

    /**
     * 查询评论列表
     * 
     * @param comment 评论
     * @return 评论
     */
    @Override
    public List<Comment> selectCommentList(Comment comment)
    {
//        return commentMapper.selectCommentList(comment);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        Set<String> rolestrs = new HashSet<>();
        for (SysRole r:roles
        ) {
            rolestrs.add(r.getRoleKey());
        }
        if (rolestrs.contains("admin")){
            return commentMapper.selectCommentList(comment);
        }else {
            // 存在多个校园，sql
            List<String> schoolIds = new ArrayList<>();
            for (String rolestr: rolestrs
            ) {
                if (rolestr.contains("xygly")){
                    String schoolid = rolestr.replace("xygly","");
                    if (!"".equals(schoolid)){
                        schoolIds.add(rolestr.replace("xygly",""));
                    }

                }
            }
            return commentMapper.selectCommentListByRole (comment,schoolIds);

        }
    }

    /**
     * 新增评论
     * 
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int insertComment(Comment comment)
    {
        //评论数加一
        Content content = ContentMapper.selectContentByContentid(comment.getContentid());
        int  Commentnum=content.getCommentnum()+1;
        content.setCommentnum(Commentnum);
        ContentMapper.updateContent(content);
        //在redis ZSet列表中修改该帖子的评论数(更新对应帖子缓存)
        double timestamp = content.getCreatetime().getTime();
        int redisRes = redisService.updateHomeContentInRedis(timestamp,content.getContentid());
        String newUUID =UUID.randomUUID().toString().replace("-","");
        comment.setCommentid(newUUID);
        comment.setUpnum(0L);
        comment.setCommentstate(0);
        //非匿名贴，指定replynickname
        if(comment.getReplyuserid()!=null && content.getIsspecial()!=1 && content.getIsspecial()!=4){
            bbs_user user=bbs_userMapper.selectbbs_userByUserid(comment.getReplyuserid());
            comment.setReplynickname(user.getNickname());
        }
        int result = commentMapper.insertComment(comment);
        try{
            if (comment.getIsmain()==1){
                //在redis 评论ZSet列表中，新增主评论
                redisService.addMainCommentToRedis(content.getSchoolid(),content.getContentid(),newUUID);
            }
            if (comment.getIsmain()==0){
                //在redis 评论ZSet列表中，对应主评论新增子评论
                Comment mainComment = commentMapper.selectCommentByCommentid(comment.getReplycommentid());
                Date date = mainComment.getCreatetime();
                double mainCommentTimestampInRedis = date.getTime();
                int res = redisService.updateChildrenCommentInRedis(content.getSchoolid(),content.getContentid(),comment.getReplycommentid(),mainCommentTimestampInRedis);
            }


        }
        catch (Exception e){
            //输出错误
            System.out.println("redisError: " + e.getMessage());
            e.printStackTrace();
            //原逻辑返回
            return result;
        }
        return result;
    }

    /**
     * 修改评论
     * 
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int updateComment(Comment comment)
    {
        //原本的评论，与更新后评论对比时间用
        mainCommentRedisVo oldComment =commentMapper.getCommentVoByCommentId(comment.getCommentid());
        int result = commentMapper.updateComment(comment);
        double oldTimestamp = oldComment.getCreateTime().getTime();
        QueryWrapper<Content> contentQueryWrapper = new QueryWrapper<>();
        contentQueryWrapper.eq("contentId", comment.getContentid());
        Content content = ContentMapper.selectOne(contentQueryWrapper);
        //主评论从下架变为正常
        if (comment.getIsmain()==1 && oldComment.getCommentState()==4 && comment.getCommentstate()!=4){
            int res = redisService.addMainCommentToRedis(content.getSchoolid(),content.getContentid(),comment.getCommentid());
        }
        //主评论从正常变成下架
        else if (comment.getIsmain()==1 && oldComment.getCommentState()!=4 && comment.getCommentstate()==4 ){
            int res = redisService.deleteMainCommentInRedis(content.getSchoolid(),content.getContentid(),comment.getCommentid(),oldTimestamp);
        }
        //主评论状态非下架，其他属性变化
        else if(comment.getIsmain()==1 && oldComment.getCommentState()!=4 && comment.getCommentstate()!=4 ){
            int res = redisService.updateMainCommentInRedis(content.getSchoolid(),content.getContentid(),comment.getCommentid(),oldTimestamp);
        }
        //子评论发生变化
        else if(comment.getIsmain()==0){
            //在redis 评论ZSet列表中，对应主评论新增子评论
            Comment mainComment = commentMapper.selectCommentByCommentid(comment.getReplycommentid());
            Date date = mainComment.getCreatetime();
            double mainCommentTimestampInRedis = date.getTime();
            int res = redisService.updateChildrenCommentInRedis(content.getSchoolid(),content.getContentid(),comment.getReplycommentid(),mainCommentTimestampInRedis);
        }
        return result;
    }

    /**
     * 批量删除评论
     * 
     * @param commentids 需要删除的评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentByCommentids(String[] commentids)
    {
        return commentMapper.deleteCommentByCommentids(commentids);
    }

    /**
     * 删除评论信息
     * 
     * @param commentid 评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentByCommentid(String commentid)
    {
        return commentMapper.deleteCommentByCommentid(commentid);
    }

    /**
     * 根据帖子ID获取评论信息（弃用）
     *
     * @param contentid 帖子ID
     * @return 结果
     */
    @Override
    public List<Comment> getCommentsByContentid(String contentid) {

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        if(contentid!=null){
            commentQueryWrapper.eq("contentid",contentid);
        }
        Comment comment = new Comment();
        comment.setContentid(contentid);
        return commentMapper.selectCommentList(comment);
    }

    /**
     * 根据帖子ID获取评论信息 +昵称
     *
     * @param contentid 帖子ID
     * @return 结果
     */
    @Override
    public List<commentVo> getCommentVosByContentid(String contentid) {
        commentVo CommentVo = new commentVo();
        CommentVo.setContentid(contentid);
        List<commentVo> list = commentMapper.selectCommentVoList(CommentVo);
        for (int i = 0; i <list.size() ; i++) {
            String userid = list.get(i).getUserid();
            String nickname = bbs_userMapper.selectbbs_userByUserid(userid).getNickname();
            list.get(i).setNickname(nickname);
        }
        return list;
    }

    @Override
    public int updateCommentState(Comment comment) {
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        if(comment.getCommentid()!=null){
            commentQueryWrapper.eq("commentid",comment.getCommentid());
        }
        Comment updateComment = commentMapper.selectOne(commentQueryWrapper);
        updateComment.setCommentstate(comment.getCommentstate());
        return commentMapper.updateById(updateComment);
    }

    @Override
    public Boolean deleteCommentListInRedis(int schoolId) {
        //清空该帖子的评论列表的redis缓存，操作时排除 Redis 相关的异常
        try{
//            //获取key前缀getCommentsPageWithType:加contentId所有的key
//            String str = "getCommentsPageWithType:" ;
//            Set keys = redisTemplate.keys(str + "*");
//            //删除相应的键值对
//            if(keys.size()>0){
//                redisTemplate.delete(keys);
//            }
//
//            //(前两条子评论)获取key前缀getTwoChildrenCommentsVO:加contentId和主评论commentId所有的key
//            String str1 = "getTwoChildrenCommentsVO:";
//            Set keys1 = redisTemplate.keys(str1 + "*");
//            //删除相应的键值对
//            if(keys1.size()>0){
//                redisTemplate.delete(keys1);
//            }
//
//            //(分页子评论)获取key前缀getChildrenCommentsPage:加contentId和主评论commentId所有的key
//            String str2 = "getChildrenCommentsPage:";
//            Set keys2 = redisTemplate.keys(str2 + "*");
//            //删除相应的键值对
//            if(keys2.size()>0){
//                redisTemplate.delete(keys2);
//            }
            //获取key前缀getCommentsPageWithType:加contentId所有的key
            String strCommentList = "HomeCommentList_" + schoolId ;
            Set keysCommentList = redisTemplate.keys(strCommentList + "*");
            //删除相应的键值对
            if(keysCommentList.size()>0){
                redisTemplate.delete(keysCommentList);
            }

        }
        catch (Exception e){
            //输出错误
            System.out.println("redisError: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
